package array;

public class 螺旋遍历二维数组 {

    class Solution2 {
        public int[] spiralArray(int[][] array) {
            if(array.length == 0)
                return new int[0];
            int x=0;
            int t=0,b=array.length-1;//表示矩阵的行数
            int l=0,r=array[0].length-1;//表示矩阵的列数
            int[] res = new int[(b+1)*(r+1)];
            while (true){
                for(int i=l;i<=r;i++)
                    res[x++] = array[t][i];
                if(++t > b) break;
                for (int i=t;i<=b;i++)
                    res[x++] = array[i][r];
                if(--r < l) break;;
                for (int i=r;i>=l;i--)
                    res[x++] = array[b][i];
                if(--b < t) break;
                for (int i=b;i>=t;i--)
                    res[x++] = array[i][l];
                if(++l > r) break;
            }
            return res;
        }
    }

    class Solution {
        boolean[][] loop;
        public int[] spiralOrder(int[][] matrix) {
            if(matrix.length == 0) return new int[0];
            int row = matrix.length;
            int col = matrix[0].length;
            int i = 0, j = 0, index = 0;//i---->row   j---->col
            loop = new boolean[row][col];
            int[] res = new int[row * col];
            while(i < row && j < col && !loop[i][j]){
                while(j < col && !loop[i][j]){
                    loop[i][j] = true;
                    res[index++] = matrix[i][j];
                    j++;
                }//向右走到头
                j--;
                i++;
                while(i < row && !loop[i][j]){
                    loop[i][j] = true;
                    res[index++] = matrix[i][j];
                    i++;
                }//向下走到头
                i--;
                j--;
                while(j >= 0 && !loop[i][j]){
                    loop[i][j] = true;
                    res[index++] = matrix[i][j];
                    j--;
                }//向左走到头
                j++;
                i--;
                while(i >= 0 && !loop[i][j]){
                    loop[i][j] = true;
                    res[index++] = matrix[i][j];
                    i--;
                }//向上走到头
                i++;
                j++;
            }
            return res;
        }
    }

}
